package org.webscale.util.sqs;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.webscale.ApplicationController;
import org.webscale.ApplicationException;

import com.xerox.amazonws.sqs2.Message;
import com.xerox.amazonws.sqs2.MessageQueue;

public class SQSListenerService  {
	static  Logger log = Logger.getLogger(SQSListenerService.class);
	
	private int poolSize;
	private  ExecutorService pool;

	public SQSListenerService(int pz){
		 this.poolSize = pz;
	}
	
	public void init(){
		 pool = Executors.newFixedThreadPool(poolSize); //TODO: figure out if you want to use cached pool or fixed pool
		 log.info("Init for SQS Service called");
		 /*
		  * 
	     SQSMessageHandler handler = (SQSMessageHandler)ApplicationController.instance().locateObject(SQS_MESSAGE_HANDLER);
		 if(handler == null){
			 log.error(SQS_MESSAGE_HANDLER + " is not defined in Beans confirguration and this service will FAIL");
			 throw new ApplicationException(SQS_MESSAGE_HANDLER + " is not defined in Beans confirguration and this service will FAIL");
		 }
		 log.info("pool Created with size =" + poolSize);
		 */	
	}
	
	public void processMessage(Message msg , MessageQueue q) {
		if(!pool.isShutdown()){
			log.debug("processing new msg " +msg.getMessageId());
			pool.execute(new MessageHandlerRunner(msg , q));
		}
	
    }
	
	public int getMaxPoolSize() {
		return poolSize;
	}

	public void shutdown() throws InterruptedException {
		log.info("shoutdown called");
		pool.shutdown();
		pool.awaitTermination(30, TimeUnit.SECONDS);
		pool.shutdownNow();
	  }
	
 }
 
 

